package com.example.springbootmodel.config.interceptor;

import com.example.springbootmodel.config.yml.ConfigYml;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: springbootmodel
 * @description: 登录拦截
 * @author: yang
 * @version: 1.0
 * @create: 2020/11/26 20:05
 **/
public class LoginHandlerInterceptor implements HandlerInterceptor {

    /**
     * 拦截请求，在访问controller调用之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * false:请求被拦截，被驳回，验证出现问题
         * true: 请求在经过验证效验以后，是OK的,是可以放行
         */
        String userName = (String) request.getSession().getAttribute("userName");
        if (!StringUtils.isEmpty(userName) || true){
            return true;
        }
        String name = request.getParameter("name");
        if(!StringUtils.isEmpty(name)){
            request.getSession().setAttribute("userName",name);
            return true;
        }
        System.out.println("进入到拦截器，被拦截。。" + request.getRequestURL().toString());
        request.setAttribute("msg","没有权限请先登陆");
        // 重定向
         response.sendRedirect(request.getContextPath() + ConfigYml.getProperty("project.html.loginHtml"));
        // 转发
        // request.getRequestDispatcher("/fronts/" + ConfigYml.getProperty("project.html.loginHtml")).forward(request,response);
        return false;
    }

    /**
     * 请求访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问controller之后，渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
